package org.openmore.platform.shiro;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.openmore.common.CommonUtils;
import org.openmore.common.exception.ForbiddenException;
import org.openmore.common.exception.OpenmoreException;
import org.openmore.platform.entity.User;
import org.openmore.platform.framework.MyThreadLocalConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by michaeltang on 2017/7/30.
 */
public class AdminRealm extends AuthorizingRealm implements IRealmClearCache{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String getName() {
        return "adminRealm";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        return super.getCredentialsMatcher();
    }

    /**
     * 自定义授权及权限管理,如果要实现自定授权及权限管理，需要继承：AuthorizingRealm
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //SuperUser superUser = (SuperUser) principals.getPrimaryPrincipal();
        logger.debug("> doGetAuthorizationInfo:" + principals.getPrimaryPrincipal().toString());
        /*try {
            User user = MyThreadLocalConfig.getUser();
            if (user.isRoot()) {
                return new SimpleAuthorizationInfo();
            }
        } catch (Exception e) {
        }*/
        //TODO:: 欠缺共享角色与权限验证
        return null;
    }

    /**
     * 清除缓存的登录信息和授权信息
     */
    public void clearCache(){
        Subject subject = SecurityUtils.getSubject();
        this.clearCache(subject.getPrincipals());
    }

    /**
     * 用于验证需要授权的信息的合法性，如果信息不合法，则抛出异常
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        throw new OpenmoreException(4001, "非法登录！");
    }

    /**
     * 重写账户密码校验方法(自己实现，不使用shiro校验)
     */
    @Override
    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
        return;
    }
}
